package com.jule.miaozhuapc.filter;

import com.jule.miaozhuapc.ano.Auth;
import com.jule.miaozhuapc.domain.WawaUser;
import com.jule.miaozhuapc.service.UserService;
import com.jule.miaozhuapc.util.WsUtil;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
   
/**
 *  登录 拦截器
 * @author Administrator
 *
 */
@Component  
public class LoginInterceptor extends HandlerInterceptorAdapter {
	
	private static Logger logger = Logger.getLogger(LoginInterceptor.class);

	@Autowired
    public  UserService userService;

    public boolean preHandle(HttpServletRequest request,  
                             HttpServletResponse response, Object handler) throws Exception {
        logger.info("进入拦截器");
        logger.info(userService + " is  userService");

        //解决Autowired为null无法注入问题
        if (userService == null) {
            WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getAutowireCapableBeanFactory().autowireBean(this);
            logger.info(userService + " is  userService");
        }

        final HandlerMethod handlerMethod = (HandlerMethod) handler;  
        final Method method = handlerMethod.getMethod();  
        final Class<?> clazz = method.getDeclaringClass();  
        if (clazz.isAnnotationPresent(Auth.class) || method.isAnnotationPresent(Auth.class)) { 
        	WawaUser user = handlerWAWATOKEN(request, userService);
        	// FIXME
            if(user  == null || "".equals(user) ){
            	logger.info(" 401 异常 TOKEN  用户 " + request.getHeader("WAWA_TOKEN"));
				response.setCharacterEncoding("utf-8");
				response.setContentType("application/json;charset=utf-8");
				response.sendError(401);
				PrintWriter out = response.getWriter();
                JSONObject rst = new JSONObject();
                JSONObject status = new JSONObject();
                status.put("code", "00000003");
                status.put("message", "未授权");
                rst.put("status", status);
				out.print(rst.toString());
				out.flush();
				return false;
            }else{  
               
            }  
        }  
        return true;  
    }  
    
    /**
     *  校验 token 用户是否登录
     * @param request
     * @return
     */
    public  WawaUser handlerWAWATOKEN(HttpServletRequest request, UserService userService2) {
       String wawa_token = request.getHeader("WAWA_TOKEN");
        logger.info(" 登录校验 WAWA_TOKEN = "+ wawa_token);

        if (wawa_token != null && !"".equals(wawa_token)) {
            WawaUser user = userService.findByToken(wawa_token);
    	    return user;
       }
        return null;
    }  
} 